﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Xml;

using DotNetNuke.Common;
using DotNetNuke.Common.Utilities;
using DotNetNuke.Entities.Modules;
using DotNetNuke.Entities.Portals;
using DotNetNuke.Modules.UserDefinedTable.Serialization;
using DotNetNuke.Services.Exceptions;
using DotNetNuke.Services.FileSystem;
using DotNetNuke.UI.Modules;

namespace DotNetNuke.Modules.UserDefinedTable
{



  public class TemplateController
  {
    private static object TemplateLock = new object();

    public static void ClearCache()
    {
      DataCache.RemoveCache(CacheKey);
    }

    public static void LoadTemplate(string Name, int portalID, int tabid)
    {
      XmlDocument document = new XmlDocument();
      document.LoadXml(Templates[Name].ExportContent);
      ModuleSerializationController.DeserializeModule(document.DocumentElement, document.DocumentElement, portalID, tabid, PortalTemplateModuleAction.Ignore, new Hashtable());
    }

    public static void LoadTemplate(XmlDocument Content, int portalID, int tabid)
    {
      ModuleSerializationController.DeserializeModule(Content.DocumentElement, Content.DocumentElement, portalID, tabid, PortalTemplateModuleAction.Ignore, new Hashtable());
    }

    public static bool SaveTemplate(string name, string description, ModuleInstanceContext context, bool forceOverwrite, int maxNumberOfRecords)
    {
      XmlDocument xmlModule = new XmlDocument();
      ModuleInfo module = new ModuleController().GetModule(context.Configuration.ModuleID, context.Configuration.TabID);
      XmlNode node = ModuleSerializationController.SerializeModule(xmlModule, module, true, maxNumberOfRecords);
      XmlElement newChild = xmlModule.CreateElement("name");
      newChild.InnerXml = context.Configuration.PaneName;
      node.AppendChild(newChild);
      TemplateInfo info4 = new TemplateInfo();
      info4.Name = name;
      info4.Description = description;
      info4.ExportContent = XSLTemplatingUtilities.PrettyPrint(node.OuterXml);
      TemplateInfo info3 = info4;
      string fileName = string.Format("{0}.{1}.module.template", Globals.CleanFileName(name), module.DesktopModule.ModuleName.ToLowerInvariant());
      PortalSettings portalSettings = context.PortalSettings;
      FolderInfo folder = Utilities.GetFolder(portalSettings, Definition.TemplateFolderName);
      if (Utilities.SaveScript(portalSettings.PortalId, info3.GetXml(), fileName, folder, forceOverwrite))
      {
        ClearCache();
        return true;
      }
      return false;
    }

    public ICollection<TemplateInfo> TemplateList()
    {
      return Templates.Values;
    }

    private static string CacheKey
    {
      get
      {
        return string.Format("UDT_Tempaltes{0}", Globals.GetPortalSettings().PortalId);
      }
    }

    public static IDictionary<string, TemplateInfo> Templates
    {
      get
      {
        IDictionary<string, TemplateInfo> cache = (IDictionary<string, TemplateInfo>)DataCache.GetCache(CacheKey);
        if (cache == null)
        {
          object templateLock = TemplateLock;
          //ObjectFlowControl.CheckForSyncLockOnValueType(templateLock);
          lock (templateLock)
          {
            cache = new Dictionary<string, TemplateInfo>();
            string[] strArray = new string[] { Globals.GetPortalSettings().HomeDirectoryMapPath + Definition.TemplateFolderName, Globals.HostMapPath + Definition.TemplateFolderName };
            foreach (string str in strArray)
            {
              if (Directory.Exists(str))
              {
                DirectoryInfo info = new DirectoryInfo(str);
                foreach (System.IO.FileInfo info2 in info.GetFiles("*.dnn_userdefinedtable.module.template"))
                {
                  try
                  {
                    XmlDocument document = new XmlDocument();
                    document.Load(info2.FullName);
                    TemplateInfo info4 = new TemplateInfo();
                    info4.Name = document.SelectSingleNode("/moduletemplate").Attributes["title"].Value;
                    info4.Description = document.SelectSingleNode("/moduletemplate").Attributes["description"].Value;
                    info4.ExportContent = document.SelectSingleNode("/moduletemplate").InnerXml;
                    TemplateInfo info3 = info4;
                    cache[info3.Name] = info3;
                  }
                  catch (Exception e)
                  {
                    
                    Exception innerException = e;
                    Exception exc = new Exception(string.Format("UDT Template: {0} caused an exception", info2.FullName), innerException);
                    DotNetNuke.Services.Exceptions.Exceptions.LogException(exc);
                    
                  }
                }
              }
              DataCache.SetCache(CacheKey, cache);
            }
          }
        }
        return cache;
      }
    }


  }

}

